package com.tangpian.sna.core.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import com.tangpian.sna.core.analysis.svm.SvmAnalyzer;

public class FileUtil {

	public static List<String> read(String inputDir, String fileCharset) {
		List<String> origins = new ArrayList<String>();

		File dir = new File(inputDir);
		File[] files = dir.listFiles();
		for (File file : files) {
			if (file.getName().endsWith(".txt")) {
				origins.addAll(readFile(file.getAbsolutePath(), fileCharset));
			}
		}

		return origins;

	}

	public static List<String> readFile(String string, String fileCharset) {
		List<String> result = new ArrayList<String>();
		try {

			InputStreamReader isr = new InputStreamReader(new FileInputStream(
					string), fileCharset);
			BufferedReader reader = new BufferedReader(isr);
			String tempString = null;

			while ((tempString = reader.readLine()) != null) {
				// Item item = parser.parse(tempString);
				// item.setId(i);
				result.add(tempString);
			}
			reader.close();
			isr.close();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	public static String getTempDir() {
		return System.getProperty("java.io.tmpdir");
	}

	public static void write(String filepath, List<String> content) {
		File file = new File(filepath);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
			for (String string : content) {
				writer.append(string + "\n");
			}
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String getFilePathFromClasspath(String file) {
		return FileUtil.class.getClassLoader().getResource(file).getFile();
		
	}
}
